package com.spring.controller;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;

/**
 * 定义拦截器对象，基于此拦截器对指定请求进行拦截。
 * @author 黄嘉强
 */
public class TimeAccessInterceptor implements HandlerInterceptor {

    /**
     * preHandle方法在@Controller方法执行之前执行。
     * @param request
     * @param response
     * @param handler
     * @return true表示放行，false或异常表示请求到此结束。
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("===preHandle===");
        LocalTime now = LocalTime.now();
        int hour = now.getHour();
        if (hour<=6 || hour >=22) {
            throw new RuntimeException("不在访问时间！");
        }

        return true;
    }
}
